package com.diankangwo.factory.controller;

import com.diankangwo.common.annotation.SysLog;
import com.diankangwo.common.utils.PageUtils;
import com.diankangwo.common.utils.Query;
import com.diankangwo.common.utils.R;
import com.diankangwo.common.validator.ValidatorUtils;
import com.diankangwo.common.validator.group.AddGroup;
import com.diankangwo.common.validator.group.UpdateGroup;
import com.diankangwo.factory.annotation.LoginUser2;
import com.diankangwo.factory.dao.TdBrowselogMapper;
import com.diankangwo.factory.dto.TdCategoryDTO;
import com.diankangwo.factory.dto.TdCommodityDTO;
import com.diankangwo.factory.entity.*;
import com.diankangwo.factory.service.*;
import com.diankangwo.sys.controller.AbstractController;
import com.diankangwo.sys.entity.SysUserEntity;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 商品controller
 * Created by wuye on 2017/9/7.
 */
@RestController
@RequestMapping("/fac/commodity")
public class TdCommodityController extends AbstractController {

    @Autowired
    private TdCommodityService commodityService;

    @Autowired
    private TdPropertyService tdPropertyService;

    @Autowired
    private TdCategoryService tdCategoryService;

    @Autowired
    private TdCommodityCategoryService tdCommodityCategoryService;

    @Autowired
    private TdCategoryPropertyService tdCategoryPropertyService;

    @Autowired
    private TdFactoryService tdFactoryService;

    @Autowired
    private TdBrowselogMapper tdBrowselogMapper;

    /**
     * 获取商品列表
     */
    @ApiOperation(value = "根据条件所有商品列表", notes = "")
    @ApiImplicitParam(name = "params", value = "查询条件", required = true, dataType = "Map<String,Object>")
    @RequestMapping("/list")
    @RequiresPermissions("fac:commodity:list")
    public R list(@RequestParam Map<String, Object> params, @LoginUser2 SysUserEntity sysUserEntity) {
        //查询列表数据
        Query query = new Query(params);
        List<TdCommodityDTO> dtoList = new ArrayList<TdCommodityDTO>();
        int total = 0;
        int saveNum = 0;
        if (sysUserEntity.getTdFactoryid() == -1) {
            //获取对应商品
            List<TdCommodity> commodityList = commodityService.queryList(query);
            total = commodityService.queryTotal(query);
            //获取的对应商品类别--》属性
            for (int i = 0; i < commodityList.size(); i++) {
                List<TdCategoryDTO> tdCategoryDTOS = new ArrayList<TdCategoryDTO>();
                TdCommodityDTO dto = new TdCommodityDTO();
                //获取商品-类别中间表数据
                List<TdCommodityCategory> tdCommodityCategory = tdCommodityCategoryService.selectByCommodityId(commodityList.get(i).getId());
                List<TdCategory> tdCategorys = new ArrayList<>();
                for (int j = 0; j < tdCommodityCategory.size(); j++) {
                    tdCategorys.add(tdCategoryService.selectByPrimaryKey(tdCommodityCategory.get(j).getCategoryId()));
                }
                for (int j = 0; j < tdCategorys.size(); j++) {
                    TdCategoryDTO tdCategoryDTO = new TdCategoryDTO();
                    tdCategoryDTO.setCategoryyname(tdCategorys.get(j).getCategoryyname());
                    tdCategoryDTO.setClasstime(tdCategorys.get(j).getClasstime());
                    tdCategoryDTO.setId(tdCategorys.get(j).getId());
                    tdCategoryDTO.setIsdelete(tdCategorys.get(j).getIsdelete());
                    tdCategoryDTO.setSortno(tdCategorys.get(j).getSortno());
                    tdCategoryDTO.setSpeciesid(tdCategorys.get(j).getSpeciesid());
                    tdCategoryDTO.setCommoditiesid(tdCategorys.get(j).getCommoditiesid());
                    List<TdCategoryProperty> tcpList = tdCategoryPropertyService.queryByCategoryId(tdCategoryDTO.getId());
                    List<TdProperty> tpList = new ArrayList<TdProperty>();
                    //获取属性
                    for (int k = 0; k < tcpList.size(); k++) {
                        TdProperty tdProperty = tdPropertyService.selectByPrimaryKey(tcpList.get(k).getPropertyId());
                        saveNum += tdProperty.getPropertynum();
                        tpList.add(tdProperty);
                    }
                    //将商品属性存入类别
                    tdCategoryDTO.setTdProperties(tpList);
                    //将类别存入DTO
                    tdCategoryDTOS.add(tdCategoryDTO);
                }
                dto.setTdCommodity(commodityList.get(i));
                dto.setTdCategoryDTOS(tdCategoryDTOS);
                dto.setReserve(saveNum);
                //将类别属性存入商品DTO
                dtoList.add(dto);
            }
        } else if (sysUserEntity.getTdFactoryid() > 0) {
            TdFactory tdFactory = tdFactoryService.queryById(sysUserEntity.getTdFactoryid());
            params.put("factoryid", tdFactory.getId());
            Query query1 = new Query(params);
            //获取对应商品
            List<TdCommodity> commodityList = commodityService.queryList(query1);
            total = commodityService.queryTotal(query1);
            for (int i = 0; i < commodityList.size(); i++) {
                List<TdCategoryDTO> tdCategoryDTOS = new ArrayList<TdCategoryDTO>();
                TdCommodityDTO dto = new TdCommodityDTO();
                //获取类别
                List<TdCommodityCategory> tdCommodityCategory = tdCommodityCategoryService.selectByCommodityId(commodityList.get(i).getId());
                List<TdCategory> tdCategorys = new ArrayList<>();
                for (int j = 0; j < tdCommodityCategory.size(); j++) {
                    tdCategorys.add(tdCategoryService.selectByPrimaryKey(tdCommodityCategory.get(j).getCategoryId()));
                }
                for (int j = 0; j < tdCategorys.size(); j++) {
                    TdCategoryDTO tdCategoryDTO = new TdCategoryDTO();
                    tdCategoryDTO.setCategoryyname(tdCategorys.get(j).getCategoryyname());
                    tdCategoryDTO.setClasstime(tdCategorys.get(j).getClasstime());
                    tdCategoryDTO.setId(tdCategorys.get(j).getId());
                    tdCategoryDTO.setIsdelete(tdCategorys.get(j).getIsdelete());
                    tdCategoryDTO.setSortno(tdCategorys.get(j).getSortno());
                    tdCategoryDTO.setSpeciesid(tdCategorys.get(j).getSpeciesid());
                    tdCategoryDTO.setCommoditiesid(tdCategorys.get(j).getCommoditiesid());
                    List<TdCategoryProperty> tcpList = tdCategoryPropertyService.queryByCategoryId(tdCategoryDTO.getId());
                    List<TdProperty> tpList = new ArrayList<TdProperty>();
                    //获取属性
                    for (int k = 0; k < tcpList.size(); k++) {
                        TdProperty tdProperty = tdPropertyService.selectByPrimaryKey(tcpList.get(k).getPropertyId());
                        saveNum += tdProperty.getPropertynum();
                        tpList.add(tdProperty);
                    }
                    //将商品属性存入类别
                    tdCategoryDTO.setTdProperties(tpList);
                    //将类别存入DTO
                    tdCategoryDTOS.add(tdCategoryDTO);
                }
                dto.setTdCommodity(commodityList.get(i));
                dto.setTdCategoryDTOS(tdCategoryDTOS);
                dto.setReserve(saveNum);
                //将类别属性存入商品DTO
                dtoList.add(dto);
            }
        }
        PageUtils pageUtil = new PageUtils(dtoList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }


    /**
     * 商品审核（参数：商品ID，审核状态0：未审核 1：已审核 2：无需审核）
     *
     * @param id
     * @param state
     * @return
     */
    @ApiOperation(value = "商品审核", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品ID", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "state", value = "商品审核状态标识:0：未审核 1：已审核 2：无需审核", required = true, dataType = "Integer")
    })
    @RequestMapping("/review")
    @RequiresPermissions("fac:commodity:review")
    public R review(int id, int state) {

        //根据ID获取商品
        TdCommodity commodity = commodityService.selectByPrimaryKey(id);
        //修改商品审核状态
        if (state == 0) {
            commodity.setCommoditycheck(false);
        } else if (state == 1) {
            commodity.setCommoditycheck(true);
        } else if (state == 2) {
            commodity.setCommoditycheck(true);
        }
        commodityService.update(commodity);
        return R.ok();
    }


    /**
     * 保存商品
     */
    @ApiOperation(value = "保存商品", notes = "")
    @ApiImplicitParam(name = "commodity", value = "商品", required = true, dataType = "TdCommodity")
    @SysLog("保存商品")
    @RequestMapping("/save")
    @RequiresPermissions("fac:commodity:save")
    public R save(@LoginUser2 SysUserEntity sysUserEntity, @RequestBody TdCommodityDTO dto) {
        TdCommodity commodity = dto.getTdCommodity();
        int speId = dto.getSpeId();
        ValidatorUtils.validateEntity(commodity, AddGroup.class);
        //保存商品
        if (commodity.getId() != null && commodity.getId() != 0) {
            commodityService.update(commodity);
            List<TdCommodityCategory> tdCommodityCategory = tdCommodityCategoryService.selectByCommodityId(commodity.getId());

            tdCommodityCategoryService.deleteByCommodityId(commodity.getId());
            for (int i = 0; i < tdCommodityCategory.size(); i++) {
                List<TdCategoryProperty> tdCategoryProperties = tdCategoryPropertyService.queryByCategoryId(tdCommodityCategory.get(i).getCategoryId());
                for (int j = 0; j < tdCategoryProperties.size(); j++) {
                    tdCategoryPropertyService.deleteByCategoryId(tdCategoryProperties.get(j).getCategoryId());
                    tdPropertyService.delete(tdCategoryProperties.get(j).getPropertyId());
                }
                tdCategoryService.deleteByPrimaryKey(tdCommodityCategory.get(i).getCategoryId());
            }

        } else {
            commodity.setCommoditypriceper(0f);
            commodity.setCommoditypricevip(0f);
            commodity.setCommodityhits(0);
            commodity.setCommodityintime(new Date());
            commodity.setFactoryid(sysUserEntity.getTdFactoryid() + "");
            commodityService.save(commodity);
        }
        for (int i = 0; i < dto.getTdCategoryDTOS().size(); i++) {
            TdCategory tc = new TdCategory();
            tc.setCategoryyname(dto.getTdCategoryDTOS().get(i).getCategoryyname());
            tc.setClasstime(dto.getTdCategoryDTOS().get(i).getClasstime());
            tc.setCommoditiesid(dto.getTdCategoryDTOS().get(i).getCommoditiesid());
            tc.setIsdelete(dto.getTdCategoryDTOS().get(i).getIsdelete());
            tc.setSortno(dto.getTdCategoryDTOS().get(i).getSortno());
            tc.setSpeciesid(dto.getTdCategoryDTOS().get(i).getSpeciesid());
            tdCategoryService.insert(tc);
            TdCommodityCategory tcc = new TdCommodityCategory();
            tcc.setCategoryId(tc.getId());
            tcc.setCommodityId(commodity.getId());
            //保存商品--》类别中间表
            tdCommodityCategoryService.save(tcc);
            List<TdProperty> tdProperties = dto.getTdCategoryDTOS().get(i).getTdProperties();
            for (int k = 0; k < tdProperties.size(); k++) {
                tdProperties.get(k).setId(null);
                tdProperties.get(k).setSpeciesid(speId);
                tdProperties.get(k).setPropertyname(tc.getCategoryyname());
                tdPropertyService.save(tdProperties.get(k));
//
                TdCategoryProperty tcp = new TdCategoryProperty();
                tcp.setCategoryId(tc.getId());
                tcp.setPropertyId(tdProperties.get(k).getId());
                //保存类别--》属性中间表
                tdCategoryPropertyService.save(tcp);
            }
        }
        return R.ok();
    }


    /**
     * 修改商品
     */
    @ApiOperation(value = "修改商品", notes = "")
    @ApiImplicitParam(name = "commodity", value = "修改商品", required = true, dataType = "TdCommodity")
    @SysLog("修改商品")
    @RequestMapping("/update")
    @RequiresPermissions("fac:commodity:update")
    public R update(@RequestBody TdCommodity commodity) {
        ValidatorUtils.validateEntity(commodity, UpdateGroup.class);

        commodityService.update(commodity);
        return R.ok();
    }

    /**
     * 删除商品
     */
    @ApiOperation(value = "删除商品", notes = "")
    @ApiImplicitParam(name = "id", value = "商品ID", required = true, dataType = "int")
    @SysLog("删除商品")
    @RequestMapping("/delete")
    @RequiresPermissions("fac:commodity:delete")
    public R delete(int id) {
//        if (tdCommodityCategoryService.selectByCommodityId(id) != null) {
//            tdCommodityCategoryService.deleteByCommodityId(id);
//        }
        TdCommodity tdCommodity = commodityService.selectByPrimaryKey(id);
        tdCommodity.setIsdelete(true);
        commodityService.update(tdCommodity);
        tdBrowselogMapper.deleteByComm(id);
//        commodityService.deleteByPrimaryKey(id);
        return R.ok();
    }

    /**
     * 查询单个商品详情
     */
    @ApiOperation(value = "查询单个商品详情", notes = "")
    @ApiImplicitParam(name = "id", value = "商品ID", required = true, dataType = "int")
    @SysLog("查询单个商品详情")
    @RequestMapping("/findById")
    @RequiresPermissions("fac:commodity:findById")
    public R findById(int id) {
        TdCommodity tdCommodity = commodityService.selectByPrimaryKey(id);
        List<TdCommodity> commodityList = new ArrayList<>();
        commodityList.add(tdCommodity);
        List<TdCommodityDTO> dtoList = new ArrayList<TdCommodityDTO>();
        List<TdCategoryDTO> tdCategoryDTOS = new ArrayList<TdCategoryDTO>();
        int saveNum = 0;
        //获取的对应商品类别--》属性
        for (int i = 0; i < commodityList.size(); i++) {
            TdCommodityDTO dto = new TdCommodityDTO();
            //获取类别
            List<TdCommodityCategory> tdCommodityCategory = tdCommodityCategoryService.selectByCommodityId(commodityList.get(i).getId());
            List<TdCategory> tdCategorys = new ArrayList<>();
            for (int j = 0; j < tdCommodityCategory.size(); j++) {
                tdCategorys.add(tdCategoryService.selectByPrimaryKey(tdCommodityCategory.get(j).getCategoryId()));
            }
            for (int j = 0; j < tdCategorys.size(); j++) {
                TdCategoryDTO tdCategoryDTO = new TdCategoryDTO();
                tdCategoryDTO.setCategoryyname(tdCategorys.get(j).getCategoryyname());
                tdCategoryDTO.setClasstime(tdCategorys.get(j).getClasstime());
                tdCategoryDTO.setId(tdCategorys.get(j).getId());
                tdCategoryDTO.setIsdelete(tdCategorys.get(j).getIsdelete());
                tdCategoryDTO.setSortno(tdCategorys.get(j).getSortno());
                tdCategoryDTO.setSpeciesid(tdCategorys.get(j).getSpeciesid());
                tdCategoryDTO.setCommoditiesid(tdCategorys.get(j).getCommoditiesid());
                List<TdCategoryProperty> tcpList = tdCategoryPropertyService.queryByCategoryId(tdCategoryDTO.getId());
                List<TdProperty> tpList = new ArrayList<TdProperty>();
                //获取属性
                for (int k = 0; k < tcpList.size(); k++) {
                    TdProperty tdProperty = tdPropertyService.selectByPrimaryKey(tcpList.get(k).getPropertyId());
                    saveNum += tdProperty.getPropertynum();
                    tpList.add(tdProperty);
                }
                //将商品属性存入类别
                tdCategoryDTO.setTdProperties(tpList);
                //将类别存入DTO
                tdCategoryDTOS.add(tdCategoryDTO);
            }
            dto.setTdCommodity(commodityList.get(i));
            dto.setTdCategoryDTOS(tdCategoryDTOS);
            dto.setReserve(saveNum);
            //将类别属性存入商品DTO
            dtoList.add(dto);
        }
        if (dtoList.size() > 0) {
            return R.ok().put("commodity", dtoList.get(0));
        } else {
            return R.ok().put("commodity", null);
        }

    }

    /**
     * 修改商品状态
     */
    @ApiOperation(value = "修改商品状态", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品ID", required = true, dataType = "int"),
            @ApiImplicitParam(name = "commodityisvouch", value = "推荐", required = true, dataType = "boolean"),
            @ApiImplicitParam(name = "ishot", value = "热门", required = true, dataType = "boolean"),
            @ApiImplicitParam(name = "commodityisnew", value = "新品", required = true, dataType = "boolean"),
            @ApiImplicitParam(name = "commodityorder", value = "排序", required = true, dataType = "int"),
            @ApiImplicitParam(name = "commoditycheck", value = "审核", required = true, dataType = "boolean")
    })
    @SysLog("修改商品状态")
    @RequestMapping("/updateStatus")
    @RequiresPermissions("fac:commodity:updateStatus")
    public R updateStatus(int id, boolean commodityisvouch, boolean ishot, boolean commodityisnew,
                          Integer commodityorder, boolean commoditycheck) {
        TdCommodity tdCommodity = commodityService.selectByPrimaryKey(id);
        tdCommodity.setCommoditycheck(commoditycheck);
        tdCommodity.setCommodityisnew(commodityisnew);
        tdCommodity.setCommodityisvouch(commodityisvouch);
        tdCommodity.setIshot(ishot);
        tdCommodity.setCommodityorder(commodityorder);
        commodityService.update(tdCommodity);
        return R.ok();
    }


//    /**
//     * 根据厂家ID获取商品
//     * @param factoryId
//     * @return
//     */
//    @ApiOperation(value = "根据厂家ID获取商品",notes = "")
//    @ApiImplicitParam(name = "factoryId",value = "厂家ID",required = true,dataType = "int")
//    @SysLog("根据厂家ID获取商品")
//    @RequestMapping("/queryByFactoryId")
//    @RequiresPermissions("fac:commodity:queryByFactoryId")
//    public R queryByFactoryId(@PathVariable int factoryId){
//        List<TdCommodity> commodities = commodityService.queryByFactoryId(factoryId);
//        int total = commodityService.queryTotalById(factoryId);
//        PageUtils pageUtil = new PageUtils(commodities, total, query.getLimit(), query.getPage());
//        return R.ok().put("page", pageUtil);
//    }

    /**
     * //     * 根据厂家ID获取商品总数
     * //     * @param factoryId
     * //     * @return
     * //
     */
    @ApiOperation(value = "根据厂家ID获取商品总数", notes = "")
    @ApiImplicitParam(name = "factoryId", value = "厂家ID", required = true, dataType = "int")
    @SysLog("根据厂家ID获取商品总数")
    @RequestMapping("/querybyTotalByFactoryId")
    @RequiresPermissions("fac:commodity:querybyTotalByFactoryId")
    public R querybyTotalByFactoryId(@PathVariable int factoryId) {
        int totle = commodityService.querybyTotalByFactoryId(factoryId);
        return R.ok().put("totle", totle);
    }

}
